<?php

namespace App\Service\Third\OceanEngine;

use App\Models\Common\ConfigModel;
use App\Remote\OceanEngine\AuthRemote;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Validation\ValidationException;

class OceanEngineService
{
    /**
     * 巨量引擎 授权码回调
     *
     * @param string $code
     * @throws GuzzleException
     * @throws ValidationException
     */
    public static function generateAuthToken(string $code)
    {
        $auth              = AuthRemote::authToken($code);
        $where             = [
            "module" => "oceanEngine",
            "name"   => "auth"
        ];
        $oceanEngineConfig = ConfigModel::query()->where($where)->first();
        if ($oceanEngineConfig) {
            $oceanEngineConfig->where("id", $oceanEngineConfig->id)->update([
                "updatedAt" => time(),
                "value"     => json_encode($auth, JSON_UNESCAPED_UNICODE)
            ]);
        } else {
            ConfigModel::query()->insert([
                "module"      => "oceanEngine",
                "name"        => "auth",
                "description" => "oceanEngine authToken (常规情况下请勿手动修改)",
                "createdAt"   => time(),
                "updatedAt"   => time(),
                "type"        => "json",
                "value"       => json_encode($auth, JSON_UNESCAPED_UNICODE)
            ]);
        }
    }
}
